package com.examination.client.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.HttpURLConnection;

/**
 * io工具类，更优雅的关闭io流
 * Created by liangtao on 2020/4/8
 */
public class IOUtils {

    private static Logger logger = LoggerFactory.getLogger(IOUtils.class);

    /**
     * 关闭输入流
     * @param in InputStream
     */
    public static void closeInputStream(InputStream in) {
        if(in != null){
            try {
                in.close();
            } catch (IOException e) {
                logger.error("close inputstream error", e);
            }
        }
    }

    /**
     * 关闭输出流
     * @param out OutputStream
     */
    public static void closeOutputStream(OutputStream out) {
        if(out != null){
            try {
                out.close();
            } catch (IOException e) {
                logger.error("close outputstream error", e);
            }
        }
    }

    /**
     * 关闭HTTP连接
     * @param conn OutputStream
     */
    public static void closeUrlConnection(HttpURLConnection conn){
        if(conn != null){
            conn.disconnect();
        }
    }

    /**
     * 关闭HTTP连接
     * @param writer OutputStream
     */
    public static void closeFileWriter(Writer writer){
        if(writer != null){
            try {
                writer.close();
            } catch (IOException e) {
                logger.error("close fileWriter error", e);
            }
        }
    }
}
